﻿/// Author: Petr Pechovic
/// Contact: http://www.pechovic.eu
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace DotNetSources.Web.UI.Buttons {

    /// <summary>
    /// Takes care of loading scripts.
    /// </summary>
    public abstract class ScriptWebControl : WebControl, IScriptControl {

        #region Ctor
        
        /// <summary>
        /// Ctor 1.
        /// </summary>
        public ScriptWebControl()
            : base() {
        }

        /// <summary>
        /// Ctor 2.
        /// </summary>
        /// <param name="tag"></param>
        public ScriptWebControl(HtmlTextWriterTag tag)
            : base(tag) {
        }

        /// <summary>
        /// Ctor 3.
        /// </summary>
        /// <param name="tag"></param>
        public ScriptWebControl(string tag)
            : base(tag) {
        }

        #endregion

        /// <summary>
        /// Called in OnPreRender. In special cases when the control doesn't have CSS file or you just want to
        /// customize it.
        /// </summary>
        protected virtual void RegisterCss() {
            Helper.RetypeToBoxContextPage(Page).RegisterCss(this.GetType());
        }

        ScriptManager sm;

        /// <summary>
        /// Register script control here and define custom CSS.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e) {

            if (!this.DesignMode) {
                sm = ScriptManager.GetCurrent(Page);
                sm.RegisterScriptControl(this);
            }
            RegisterCss();
            base.OnPreRender(e);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer) {
            if (!this.DesignMode) {
                sm.RegisterScriptDescriptors(this);
            }
            base.Render(writer);
        }

        #region IScriptControl Members

        /// <summary>
        /// Leave to concrete implementation.
        /// </summary>
        /// <returns></returns>
        public abstract IEnumerable<ScriptDescriptor> GetScriptDescriptors();

        /// <summary>
        /// Leave to concrete implementation.
        /// </summary>
        /// <returns></returns>
        public abstract IEnumerable<ScriptReference> GetScriptReferences();

        #endregion
    }

}
